/*
 * @Author: panghu chenjh@datamargin.com
 * @Date: 2024-04-11 17:13:22
 * @LastEditors: panghu chenjh@datamargin.com
 * @LastEditTime: 2024-05-03 22:23:12
 * @FilePath: \zheye\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'

// 创建路由规则
const routes: Array<RouteRecordRaw> = [
  { path: '/', component: () => import('@/views/home.vue'), name: 'home' },
  { path: '/login', component: () => import('@/views/login.vue'), name: 'login', meta: { redirectedAlreadyLogin: true } },
  { path: '/signUp', component: () => import('@/views/signUp.vue'), name: 'signUp', meta: { redirectedAlreadyLogin: true } },
  { path: '/column/:id', component: () => import('@/views/columnDetail.vue'), name: 'column' },
  { path: '/create', component: () => import('@/views/createPost.vue'), name: 'createPost', meta: { requiredLogin: true } },
  { path: '/posts/:id', component: () => import('@/views/PostDetail.vue'), name: 'postDetail', meta: { requiredLogin: true } },
  { path: '/:pathMatch(.*)*', redirect: '/' }
]

// 创建router实列
const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const { token, user } = store.state
  const { requiredLogin, redirectedAlreadyLogin } = to.meta
  if (!user.isLogin) {
    if (token) {
      store.dispatch('fetchCurrentUser').then(_ => {
        if (redirectedAlreadyLogin) {
          next('/')
        } else {
          next()
        }
      }).catch(res => {
        store.commit('LOGOUT')
        next('/login')
      })
    } else if (requiredLogin) {
      next('/login')
    } else {
      next()
    }
  } else { // 已登录
    if (redirectedAlreadyLogin) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
